package com.itcg.library.service.imp;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itcg.library.mapper.BooksMapper;
import com.itcg.library.pojo.Books;
import com.itcg.library.pojo.BooksPageQuery;
import com.itcg.library.pojo.PageBean;
import com.itcg.library.service.BooksService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

//操作Books的业务层接口实现类
@Service
public class BooksServiceImpl implements BooksService {
    private static final Logger log = LoggerFactory.getLogger(BooksServiceImpl.class);
    @Autowired
    private BooksMapper booksMapper;

    @Override
    public void insert(Books books) {
        booksMapper.insert(books);
    }

    @Override
    public void batchDelete(List<Integer> ids) {
        booksMapper.batchDelete(ids);
    }

    @Override
    public void updates(Books books) {
        booksMapper.updates(books);
    }

    @Override
    public Books findById(Integer id) {
        return booksMapper.findById(id);
    }

    @Override
    public PageBean<Books> findByConditions(BooksPageQuery booksPageQuery) {
        Integer PageNum = booksPageQuery.getPageNum();
        if (PageNum == null) {
            PageNum = 1;
        }
        Integer PageSize = booksPageQuery.getPageSize();
        if (PageSize == null) {
            PageSize = 3;
        }
        PageHelper.startPage(PageNum, PageSize);
        List<Books> booksList = booksMapper.findByConditions(booksPageQuery);

        PageInfo<Books> info = new PageInfo<>(booksList);
        PageBean<Books> booksPageQueryPageBean = new PageBean<>();

        booksPageQueryPageBean.setTotalCount(info.getTotal());
        booksPageQueryPageBean.setPageSize(PageSize);
        booksPageQueryPageBean.setPageNum(PageNum);
        booksPageQueryPageBean.setTotalPage(info.getPages());
        booksPageQueryPageBean.setDataList(booksList);
        return booksPageQueryPageBean;
    }

    @Override
    public PageBean<Books> findByConditions2(BooksPageQuery booksPageQuery) {
        Integer pageNum = booksPageQuery.getPageNum();
        if (pageNum == null) {
            pageNum = 1;
        }
        Integer pageSize = booksPageQuery.getPageSize();
        if (pageSize == null) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Books> booksList = booksMapper.findByConditions2(booksPageQuery);
        PageInfo<Books> info = new PageInfo<>(booksList);

        PageBean<Books> pageBean = new PageBean<>();
        pageBean.setPageNum(pageNum);
        pageBean.setPageSize(pageSize);
        pageBean.setTotalPage(info.getPages());
        pageBean.setTotalCount(info.getTotal());
        pageBean.setDataList(booksList);
        return pageBean;
    }

}